import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Table, Form, Input, Button, Select, Space, Tag, Modal, message, Popconfirm, Switch, Row, Col } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, SearchOutlined, ReloadOutlined } from '@ant-design/icons';
import { request } from 'umi';
import AuthorizedButton from '@/components/Authorized/AuthorizedButton';

const { Option } = Select;

// 获取城市列表
const fetchCities = async (params) => {
  return request('/api/v1/city', {
    method: 'GET',
    params,
  });
};

// 获取城市详情
const fetchCityDetail = async (id) => {
  return request(`/api/v1/city/${id}`, {
    method: 'GET',
  });
};

// 创建城市
const createCity = async (data) => {
  return request('/api/v1/city', {
    method: 'POST',
    data,
  });
};

// 更新城市
const updateCity = async (data) => {
  return request('/api/v1/city', {
    method: 'PUT',
    data,
  });
};

// 删除城市
const deleteCity = async (id) => {
  return request(`/api/v1/city/${id}`, {
    method: 'DELETE',
  });
};

const CityList = () => {
  const [cities, setCities] = useState([]);
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const [cityForm] = Form.useForm();
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [searchParams, setSearchParams] = useState({});
  const [formVisible, setFormVisible] = useState(false);
  const [currentCity, setCurrentCity] = useState(null);
  const [formTitle, setFormTitle] = useState('创建城市');

  // 获取城市列表
  const fetchCityList = async () => {
    try {
      setLoading(true);
      const res = await fetchCities({
        page: pagination.current,
        pageSize: pagination.pageSize,
        ...searchParams,
      });
      if (res.success) {
        setCities(res.data.list || []);
        setPagination({
          ...pagination,
          total: res.data.total,
        });
      } else {
        message.error(res.message || '获取城市列表失败');
      }
    } catch (error) {
      console.error('获取城市列表出错:', error);
      message.error('获取城市列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchCityList();
  }, [pagination.current, pagination.pageSize, searchParams]);

  // 处理添加城市
  const handleAdd = () => {
    setFormTitle('创建城市');
    setCurrentCity(null);
    cityForm.resetFields();
    cityForm.setFieldsValue({
      status: 1,
    });
    setFormVisible(true);
  };

  // 处理编辑城市
  const handleEdit = (record) => {
    setFormTitle('编辑城市');
    setCurrentCity(record);
    cityForm.resetFields();
    cityForm.setFieldsValue({
      name: record.name,
      sort: record.sort,
      status: record.status,
    });
    setFormVisible(true);
  };

  // 处理删除城市
  const handleDelete = async (id) => {
    try {
      setLoading(true);
      const res = await deleteCity(id);
      if (res.success) {
        message.success('删除城市成功');
        fetchCityList();
      } else {
        message.error(res.message || '删除城市失败');
      }
    } catch (error) {
      console.error('删除城市出错:', error);
      message.error('删除城市失败');
    } finally {
      setLoading(false);
    }
  };

  // 提交表单
  const handleFormSubmit = async () => {
    try {
      const values = await cityForm.validateFields();
      setLoading(true);
      
      let res;
      if (currentCity) {
        // 更新
        res = await updateCity({
          id: currentCity.id,
          ...values,
        });
      } else {
        // 创建
        res = await createCity(values);
      }
      
      if (res.success) {
        message.success(`${currentCity ? '更新' : '创建'}城市成功`);
        setFormVisible(false);
        fetchCityList();
      } else {
        message.error(res.message || `${currentCity ? '更新' : '创建'}城市失败`);
      }
    } catch (error) {
      console.error(`${currentCity ? '更新' : '创建'}城市出错:`, error);
      message.error(`${currentCity ? '更新' : '创建'}城市失败`);
    } finally {
      setLoading(false);
    }
  };

  // 处理搜索
  const handleSearch = (values) => {
    const params = {};
    if (values.name) {
      params.name = values.name;
    }
    if (values.status !== undefined) {
      params.status = values.status;
    }
    
    setSearchParams(params);
    setPagination({
      ...pagination,
      current: 1,
    });
  };

  // 处理重置
  const handleReset = () => {
    form.resetFields();
    setSearchParams({});
    setPagination({
      ...pagination,
      current: 1,
    });
  };

  // 表格列定义
  const columns = [
    {
      title: '城市名称',
      dataIndex: 'name',
      key: 'name',
      width: 180,
    },
    {
      title: '排序',
      dataIndex: 'sort',
      key: 'sort',
      width: 100,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => (
        <Tag color={status === 1 ? 'green' : 'red'}>
          {status === 1 ? '启用' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 180,
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <AuthorizedButton
            permission="city:update"
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </AuthorizedButton>
          <Popconfirm
            title="确定要删除此城市吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <AuthorizedButton 
              permission="city:delete"
              type="link" 
              icon={<DeleteOutlined />} 
              danger
            >
              删除
            </AuthorizedButton>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 处理表格变化
  const handleTableChange = (pagination, filters, sorter) => {
    setPagination(pagination);
  };

  return (
    <PageContainer>
      <Card
        title="城市管理"
        extra={
          <AuthorizedButton permission="city:create" type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
            创建城市
          </AuthorizedButton>
        }
      >
        <Form
          form={form}
          layout="inline"
          style={{ marginBottom: 24 }}
        >
          <Row gutter={24} style={{ width: '100%' }}>
            <Col span={6}>
              <Form.Item name="name" label="城市名称">
                <Input placeholder="请输入城市名称" allowClear />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="status" label="状态">
                <Select placeholder="请选择状态" allowClear>
                  <Option value={1}>启用</Option>
                  <Option value={0}>禁用</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={12} style={{ textAlign: 'right' }}>
              <Form.Item>
                <Button type="primary" onClick={() => handleSearch(form.getFieldsValue())} style={{ marginRight: 8 }}>
                  搜索
                </Button>
                <Button onClick={handleReset}>
                  重置
                </Button>
              </Form.Item>
            </Col>
          </Row>
        </Form>
        
        <Table
          columns={columns}
          dataSource={cities}
          rowKey="id"
          loading={loading}
          pagination={pagination}
          onChange={handleTableChange}
          scroll={{ x: 800 }}
        />
      </Card>

      {/* 城市表单弹窗 */}
      <Modal
        title={formTitle}
        visible={formVisible}
        onCancel={() => setFormVisible(false)}
        footer={null}
        width={500}
        destroyOnClose
      >
        <Form
          form={cityForm}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 18 }}
          onFinish={handleFormSubmit}
        >
          <Form.Item label="城市名称" name="name" rules={[{ required: true, message: '请输入城市名称' }]}>
            <Input placeholder="请输入城市名称" />
          </Form.Item>
          <Form.Item label="排序" name="sort" initialValue={0}>
            <Input type="number" placeholder="请输入排序值" />
          </Form.Item>
          <Form.Item label="状态" name="status" initialValue={1}>
            <Select placeholder="请选择状态">
              <Option value={1}>启用</Option>
              <Option value={0}>禁用</Option>
            </Select>
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" loading={loading}>
                提交
              </Button>
              <Button onClick={() => setFormVisible(false)}>取消</Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default CityList;